package com.file;

import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
 * Created by Jeff on 2018/8/15.
 */
public class CopyFileThread extends Thread {

    private String srcPath;
    private String descPath;
    private long start, end;

    public CopyFileThread(String srcPath, String descPath, long start, long end) {
        this.srcPath = srcPath;
        this.descPath = descPath;
        this.start = start;
        this.end = end;
    }


    @Override
    public void run() {
        try {
            long startTime = System.currentTimeMillis();
            //创建只读的随机访问文件
            RandomAccessFile in = new RandomAccessFile(srcPath, "r");
            //创建可读写的随机访问文件
            RandomAccessFile out = new RandomAccessFile(descPath, "rw");
            //经输入跳转到指定位置
            in.seek(start);
            //从指定位置开始写
            out.seek(start);
            //文件输入通道
            FileChannel inChannel = in.getChannel();
            FileChannel outChannel = out.getChannel();
            //锁住需要操作的区域，false代表锁住
            FileLock lock = outChannel.lock(start, (end - start), false);
            //将字节从此通道的文件传输到给定的可写入字节的输出通道
            inChannel.transferTo(start, (end - start), outChannel);
            //释放锁
            lock.release();
            //从里到外关闭文件
            out.close();
            in.close();
            long endTime = System.currentTimeMillis();
            String time = endTime - startTime + "ms";
            System.out.println(time);
        } catch (Exception e) {

        }
    }
}

